package com.weirdor.elasticsearch.kit;

import com.alibaba.fastjson.JSONObject;
import com.weirdor.elasticsearch.utils.ObjectUtils;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.convert.Convert;
import java.util.*;

/**
 * Created by weirdor on 2017/12/19.
 * 文件描述：json转化
 */
public class ElasticSearchJsonObjectKit {

    public static JSONObject toJsonObject(Object obj) {

        Map<String, Object> map = new HashMap<>();

        if (JSONObject.class.isInstance(obj)) {
            return (JSONObject) obj;
        }
        if (BeanUtil.isBean(obj.getClass())){
            map = ElasticSearchKit.INSTANCE.toMap(obj);
        }
        if (Map.class.isInstance(obj)) {
            map = (Map<String, Object>) obj;
        }
        if (String.class.isInstance(obj)){
            return ObjectUtils.isJSONObject(obj);
        }

        for (Map.Entry<String, Object> entry : map.entrySet()) {

            if (entry.getValue() instanceof ElasticSearchBean) {
                JSONObject doc = toJsonObject((ElasticSearchBean) entry.getValue());
                map.put(entry.getKey(), doc);
            }

            if (entry.getValue() instanceof List) {
                try {
                    List<ElasticSearchBean> list = (List<ElasticSearchBean>) entry.getValue();
                    List<JSONObject> docList = new ArrayList<JSONObject>();
                    list.forEach(k->{
                        JSONObject doc = toJsonObject(k);
                        docList.add(doc);
                    });
                    map.put(entry.getKey(), docList);
                } catch (RuntimeException e) {
                    ElasticSearchKit.INSTANCE.error("ElasticSearchJsonObjectKit .class",
                            "The list must be List<ElasticSearchBean> inserted into the database.");
                }

            }
        }
        String id = Convert.toStr(map.get("id"));
        if (id == null || id.equals("")) {
            map.remove("id");
        }

        return new JSONObject(map);
    }

    public static JSONObject toJsonObject(ElasticSearchBean bean) {
        return new JSONObject(bean.toMap());
    }

    /* 用于判断是否是基本类型和JSON对象，如果是的话不需要进行转换 */
    public static boolean conversionValidation(Object obj) {
        if (String.class.isInstance(obj) || Integer.class.isInstance(obj)
                || Double.class.isInstance(obj) || Boolean.class.isInstance(obj)
                || Float.class.isInstance(obj) || Character.class.isInstance(obj)
                || Long.class.isInstance(obj) || Byte.class.isInstance(obj)
                || Short.class.isInstance(obj) || Date.class.isInstance(obj)
                || Map.class.isInstance(obj)) {
            return false;
        }

        if (obj instanceof Object) {
            return true;
        }

        return false;

    }


}
